<?
if(!$_SESSION) session_start();
class softrDB{
	var $query="", $id="", $error="";
	function softrDB($file,$id){	
		$this->id=$id."fileJSON";
		$json = new Services_JSON();	
		$_SESSION[$this->id]= $json->decode(is_file($file) ? file_get_contents($file) : $file);
	}
	function loadQuery($modulo,$id,$params=null,$isCount=false){
		if(!$_SESSION[$this->id]->$modulo->$id){
			$this->error= "Query con id -".$id."- en el m&oacute;dulo -".$modulo."- no existe.";
		}else{
			$query = $_SESSION[$this->id]->$modulo->$id;
			$params=explode("|",$params);
			$varparams=$this->getParams($query);
			$this->query= str_replace($varparams,$params,$query);
			return ($isCount===false) ? $this->executeQuery() : $this->countQuery();
		}
	}
	function loadCountQuery($file,$modulo,$query,$params=null){
		return $this->loadQuery($file,$modulo,$query,$params,true); 
	}
	function countQuery(){
		$rs=mysql_query($this->query);
		return mysql_result($rs,0,0);
	}
	function executeQuery(){
		$rs=mysql_query($this->query) or die(mysql_error());
		
		if(strpos(strtoupper($this->query),"UPDATE")!==0 && strpos($this->query,"SET")!==0 && strpos($this->query,"INSERT")!==0  && strpos($this->query,"DELETE")!==0){
			if(mysql_num_rows($rs)==1 && mysql_num_fields($rs)==1) return mysql_result($rs,0,0);
			$rw=array();
			while($rw1=mysql_fetch_assoc($rs)) array_push($rw,$rw1);
			return $rw;
		}
	}
	function outQuery(){
		echo $this->query."<br />";
	}
	function outResultSet(){
		$rs=mysql_query($this->query);
		while($rw=mysql_fetch_assoc($rs)){
			echo "<pre>";print_r($rw);echo "</pre>";
		}
	}
	function getParams($strParams){
		preg_match_all('/\?\w+/', $strParams,$params);
		$params=$params[0];
		$params=array_unique($params);
		sort($params,SORT_STRING);
		reset($params);
		return $params;
	}
}
?>